package com.clippick.history;

import java.io.File;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
//import android.content.SharedPreferences;
import android.net.Uri;
//import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.ClipboardManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import co.kr.clippick.R;

import com.clippick.MainActivity;
import com.clippick.common.Dialogs;
import com.clippick.common.GlobalValue;
import com.clippick.common.Toasts;
//import com.clippick.database.ClipData;
import com.clippick.database.FeedOrderDBAdapter;
import com.clippick.database.HistoryDBAdapter;
import com.clippick.dbbusiness.DBBusiness;
import com.clippick.ui.MultiDirectionSlidingDrawer;
import com.clippick.ui.MultiDirectionSlidingDrawer.OnDrawerCloseListener;
import com.clippick.ui.MultiDirectionSlidingDrawer.OnDrawerOpenListener;

@SuppressWarnings({ "deprecation","rawtypes" })
public class HistoryFragment extends Fragment implements OnItemClickListener {
	// common
	private Context mContext;
	private DisplayMetrics metrics;
	private View view;
	private MainActivity parent;

	// system cliboard
	private ClipboardManager systemClipboard;

	/** local database manager */
	/**
	private HistoryDBAdapter dbManager;
	private FeedOrderDBAdapter feedOrderDbManager;
	*/
	
	// view
	private ListView list;
	private View footerView = null;
	private ImageView clipBottom, starBottom, settingBottom;

	// view: memo
	private Button sendButton;
	private EditText memoText;
	private static MultiDirectionSlidingDrawer memo;
	public static boolean isMemoClose = true;

	// adapter
	private HistoryAdapter adapter;

	/**
	// data:info
	private SharedPreferences pref;
	private SharedPreferences.Editor editor;
	*/
	
	// clip list
	private List<Map> items;
	private static int itemPosition = -1;

	// memo clip
	private String memoClip = "";

	// start view
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext = (Context) getActivity();
		parent = (MainActivity) mContext;
		view = inflater.inflate(R.layout.history, container, false);
		metrics = mContext.getResources().getDisplayMetrics();

		// check bundle data is star menu or history menu
		boolean isStarClip = false;
		if (getArguments() != null) {
			isStarClip = getArguments().getBoolean("star");
		}

		// find UI view
		clipBottom = (ImageView) view.findViewById(R.id.history_bottom);
		starBottom = (ImageView) view.findViewById(R.id.star_bottom);
		settingBottom = (ImageView) view.findViewById(R.id.setting_bottom);

		// set UI Button-bottom visible
		if (getArguments() != null) {
			if (getArguments().getBoolean("star")) {
				clipBottom.setVisibility(View.INVISIBLE);
				starBottom.setVisibility(View.VISIBLE);
				settingBottom.setVisibility(View.INVISIBLE);
			}
		} else {
			clipBottom.setVisibility(View.VISIBLE);
			starBottom.setVisibility(View.INVISIBLE);
			settingBottom.setVisibility(View.INVISIBLE);
		}
		
		/**
		// set database
		dbManager = parent.getLocalDb();
		feedOrderDbManager = parent.getLocalOrderDb();
		*/
		
		// set systemClipboard
		systemClipboard = parent.getSystemClipboard();

		// find view
		list = (ListView) view.findViewById(R.id.clip_list);
		list.setOnItemClickListener(this);
		registerForContextMenu(list);

		// set footer
		if (isStarClip)
			list.addFooterView(getFooterView());
		else
			list.removeFooterView(getFooterView());

		// set action: footer view
		footerView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.i("footer", "view");
				parent.getTinyUrl();
			}
		});

		// set adapter
		adapter = new HistoryAdapter(mContext);
		list.setAdapter(adapter);

		// find memo view
		memo = (MultiDirectionSlidingDrawer) view.findViewById(R.id.drawer);
		memoText = (EditText) view.findViewById(R.id.memo);
		sendButton = (Button) view.findViewById(R.id.send);

		// optimizing margin size sendButton for each devices.
		setSendButtonMargins();

		// memo open action
		memo.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			@Override
			public void onDrawerOpened() {
				// TODO Auto-generated method stub
				isMemoClose = false;
				// Log.i("memo", "open");
			}
		});

		// memo close action
		memo.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			@Override
			public void onDrawerClosed() {
				// TODO Auto-generated method stub
				isMemoClose = true;
				// Log.i("memo", "close");
				InputMethodManager imm = (InputMethodManager) mContext
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(memoText.getWindowToken(), 0);
			}
		});

		// memo open initial value
		isMemoClose = true;
		InputMethodManager imm = (InputMethodManager) mContext
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(memoText.getWindowToken(), 0);

		// memo button action
		sendButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (memoText.getText().toString().equals("")) {

				} else {
					// send
					memoClip = memoText.getText().toString();
					// systemClipboard.setText(memoClip);
					parent.insertMemoClip(memoClip);

					// hide
					memoText.setText("");
					memo.animateClose();
					InputMethodManager imm = (InputMethodManager) mContext
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(memoText.getWindowToken(), 0);

					// notify
					// Toasts.showToast(mContext,
					// "Your memo is put in your clipboard!");
					// parent.rotateIcon(R.id.history_button);
				}
			}
		});

		IntentFilter filterUpdatePolling = new IntentFilter();
		filterUpdatePolling.addAction("com.clippick.UpdatePolling");
		parent.registerReceiver(updatePolling, filterUpdatePolling);

		IntentFilter filterShowIndicator = new IntentFilter();
		filterShowIndicator.addAction("com.clippick.showIndicator");
		parent.registerReceiver(showIndicator, filterShowIndicator);

		// update latest clip
		updateClipList(isStarClip);

		return view;
	}

	// set sendButton margin to optimize for variety of devices screen size and
	// density
	@SuppressWarnings("static-access")
	private void setSendButtonMargins() {
		final float scale = metrics.density;
		int pixels = (int) (70 * scale + 0.5f);
		int leftMarginPixels = (int) (35 * scale + 0.5f);
		int topMarginPixels = (int) (195 * scale + 0.5f);

		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				pixels, pixels);
		lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

		// lp.setMargins(left, top, right, bottom);
		lp.setMargins(0, topMarginPixels, leftMarginPixels, 0);

		if (metrics.densityDpi == metrics.DENSITY_HIGH) {
			// supports: samsung galaxy S2
			pixels = (int) (70 * scale + 0.5f);
			leftMarginPixels = (int) (35 * scale + 0.5f);
			topMarginPixels = (int) (215 * scale + 0.5f);
			lp.setMargins(0, topMarginPixels, leftMarginPixels, 0);
			sendButton.setLayoutParams(lp);

		} else if (metrics.densityDpi == metrics.DENSITY_XHIGH) {
			// supports: google reference phone galaxy nexus
			sendButton.setLayoutParams(lp);
		}
	}

	// create footer view
	private View getFooterView() {
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		footerView = inflater.inflate(R.layout.invite_footer, null);
		return footerView;
	}

	// listView long press: contextMenu
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		if (items != null) {
			Map clip = items.get(info.position);
			menu.setHeaderTitle("Select Menu");

			if (clip != null) {
				// check image data
				if (!clip.get(FeedOrderDBAdapter.KEY_DB_IMAGE_URL).toString()
						.equals("")) {
					menu.add(0, 1, 0, "Move to gallery");
				} else {
					menu.add(0, 0, 0, "Copy Clip");
				}

				if (clip.get(HistoryDBAdapter.KEY_DB_KEEPBOX).toString()
						.equals("1")) {
					// menu.add(0, 2, 0, "Remove star");
				} else {
					// menu.add(0, 3, 0, "Add star");
				}
				menu.add(0, 5, 0, "Share To");
				menu.add(0, 4, 0, "Delete Clip");
			}

		} else {
			Toasts.showToast(mContext, "wrong clip selected!");
		}
	}

	// listView long press: contextMenu: controller
	public boolean onContextItemSelected(MenuItem item) {
		// progress dialog
		Dialogs.showDialog(mContext, "Loading");

		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		@SuppressWarnings("unchecked")
		final Map<String, String> clip = items.get(info.position);
		final String index = clip.get(HistoryDBAdapter.KEY_DB_NO).toString();
		final String content = clip.get(HistoryDBAdapter.KEY_DB_CONTENTS)
				.toString();

		switch (item.getItemId()) {
		case 0:
			// Copy Clip
			GlobalValue.isOnInsertSync = true;
			GlobalValue.AppClip = content;
			systemClipboard.setText(content);
			 Toasts.showToast(mContext, "It's put in your clipboard");
			break;
		case 1:
			// Move to Gallery
			parent.sendImageGallery(clip);
			Toasts.showToast(mContext, "Image saved!");
			break;
		case 2:
			// Remove Star
			if (getArguments().getBoolean("star") && itemPosition != -1) {
				clip.put(HistoryDBAdapter.KEY_DB_KEEPBOX, "0");
				items.add(itemPosition, clip);
				adapter.notifyDataSetChanged();
			}
			parent.setStar(clip);
			break;
		case 3:
			// Add Star
			parent.setStar(clip);
			break;
		case 4:
			// Delete Clip
			items.remove(clip);
			adapter.notifyDataSetChanged();
			parent.deleteClip(index);
			break;

		case 5:
			// Share
			shareMenu(clip);
			break;
		}

		Dialogs.dismissDialog(mContext);
		return true;
	}

	private void shareMenu(Map<String, String> clip) {
		// check text or image
		String imageUri = clip.get(HistoryDBAdapter.KEY_DB_IMG).toString();
		String text = clip.get(HistoryDBAdapter.KEY_DB_CONTENTS).toString();

		if (imageUri.equals("")) {
			// 텍스트
			if (!text.startsWith("_", 0) && !(text.length() == 14)) {
				Intent sendIntent = new Intent();
				sendIntent.setAction(Intent.ACTION_SEND);
				sendIntent.putExtra(Intent.EXTRA_TEXT, text);
				sendIntent.setType("text/plain");
				startActivity(Intent.createChooser(sendIntent, "send to"));
			}
		} else {
			// 이미지
			String path = clip.get(FeedOrderDBAdapter.KEY_DB_TEXT_PATH)
					.toString();
			File imageFile = new File(path);
			Uri uriToImage = Uri.fromFile(imageFile);
			Intent shareIntent = new Intent();
			shareIntent.setAction(Intent.ACTION_SEND);
			shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
			shareIntent.setType("image/*");
			startActivity(Intent.createChooser(shareIntent, "send to"));
		}
	}

	// activity life-cycle
	public void onResume() {
		super.onResume();

		IntentFilter filterUpdatePolling = new IntentFilter();
		filterUpdatePolling.addAction("com.clippick.UpdatePolling");
		parent.registerReceiver(updatePolling, filterUpdatePolling);

		IntentFilter filterShowIndicator = new IntentFilter();
		filterShowIndicator.addAction("com.clippick.showIndicator");
		parent.registerReceiver(showIndicator, filterShowIndicator);
	}

	public void onDestroy() {
		super.onDestroy();
		parent.unregisterReceiver(updatePolling);
		parent.unregisterReceiver(showIndicator);
	}

	/** 데이터에 변화가 생기면 뷰를 갱신한다 */
	BroadcastReceiver updatePolling = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {

			// check bundle data is star menu or history menu
			boolean isStarClip = false;
			if (getArguments() != null) {
				isStarClip = getArguments().getBoolean("star");
			}

			// 데이터를 Map 형식으로 바꿔온다
			updateClipList(isStarClip);

			// dismiss indicator
			parent.handleIndicator(false);

			// pie chart
			// TabFragment tab = new TabFragment();
			// tab.setPieChart(mContext);
			// parent.updatePie();

			GlobalValue.IS_UPDATING = false;
		}
	};

	public void updateFeed() {
		// check bundle data is star menu or history menu
		boolean isStarClip = false;
		if (getArguments() != null) {
			isStarClip = getArguments().getBoolean("star");
		}

		// 데이터를 Map 형식으로 바꿔온다
		updateClipList(isStarClip);
	}

	BroadcastReceiver showIndicator = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getExtras() != null) {
				// show indicator
				parent.handleIndicator(intent.getExtras().getBoolean("show"));
				Log.i("indicator", "boolean : "
						+ intent.getExtras().getBoolean("show"));
			}
		}
	};

	/** Database에 저장된 클립을 가져와서 리스트뷰를 다시 생성한다 */
	private void updateClipList(boolean isStarClip) {
		if (!isStarClip){
			//items = ClipData.fetchClipFromDb(dbManager, feedOrderDbManager);
			items = DBBusiness.fetchClipFromDb();
			if (!items.isEmpty()) {
				if (items.get(0).containsKey("error")) {
					if (items.get(0).get("error").toString().equals("no such table")) {
						
					}
				}
			}
		}else{
			//items = ClipData.fetchStarClipFromDb(dbManager, feedOrderDbManager);
			items = DBBusiness.fetchStarClipFromDb();
		}
		adapter.addClipData(items);
		adapter.notifyDataSetChanged();
	}

	/** Text Clip의 경우, 클립보드로 밀어넣고 이미지의 경우, fullScreenViewer를 보여준다 */
	public void onItemClick(AdapterView<?> parent, View v, int position,
			long arg3) {
		itemPosition = position;
		Map clip = items.get(position);
		GlobalValue.isOnInsertSync = true;

		String imageUri = clip.get(HistoryDBAdapter.KEY_DB_IMG).toString();
		String text = clip.get(HistoryDBAdapter.KEY_DB_CONTENTS).toString();

		if (imageUri.equals("")) {
			// 텍스트는 클립보드로 밀어넣는다
			if (!text.startsWith("_", 0) && !(text.length() == 14)
					&& !text.equals("[img0]")) {
				GlobalValue.AppClip = text;
				GlobalValue.PrevClip = text;
				systemClipboard.setText(text);
				Toasts.showToast(mContext, "It's put in your clipboard");
			}
		} else {
			// 이미지는 큰 화면으로 보기 이동
			String path = clip.get(FeedOrderDBAdapter.KEY_DB_TEXT_PATH)
					.toString();
			// String path =
			// clip.get(FeedOrderDBAdapter.KEY_DB_IMAGE_URL).toString();
			MainActivity main = (MainActivity) mContext;
			main.showFullScreenViewer(path);
		}
	}

	public static void closeMemo() {
		memo.animateClose();
	}
}
